package com.company.Nio;

import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;

public class NioTest {

    /**
     * 写入文件
     *
     * @throws Exception
     */
    @Test
    public void test01() throws Exception {
        //创建输出流
        FileOutputStream fos = new FileOutputStream(new File("basic.txt"));
        //得到通道
        FileChannel fc = fos.getChannel();
        //得到缓冲区
        ByteBuffer bf = ByteBuffer.allocate(1024);
        String str = "hello，nio,德萨";
        bf.put(str.getBytes());//将数据写入到缓冲区
        bf.flip(); //将通道的指针位置调到初始位置
        //把缓冲区写入到通道中
        fc.write(bf);
        //关闭
        fos.close();
    }

    /**
     * 读取文件
     */
    @Test
    public void test02() throws Exception {
        File file = new File("basic.txt");

        FileInputStream fis = new FileInputStream(file);
        //得到一个通道
        FileChannel fc = fis.getChannel();
        //使用缓冲
        ByteBuffer buffer = ByteBuffer.allocate((int) file.length()); //缓冲区跟文件大小一致
        //从通道读取数据到buffer
        fc.read(buffer);

        System.out.println(new String(buffer.array()));
        //关闭
        fis.close();
    }

    /**
     * 拷贝文件
     */
    @Test
    public void test03() throws Exception {
        FileInputStream fis = new FileInputStream("basic.txt");
        FileOutputStream fos = new FileOutputStream("basic2.txt");
        //得到两个通道
        FileChannel sourceFC = fis.getChannel();
        FileChannel descFC = fos.getChannel();
        //复制
        descFC.transferFrom(sourceFC, 0, sourceFC.size());

        fis.close();
        fos.close();

    }

}
